package main

import (
    "../pb"
    "../server"
    "gopkg.in/alecthomas/kingpin.v2"
    "github.com/kpango/glg"
    "github.com/utahta/go-cronowriter"
    "net"
    "google.golang.org/grpc"
)

func main() {
    authCfg := kingpin.Flag("auth", "the auth file").Default("auth.json").String()
    addr := kingpin.Flag("addr", "listen addr").Default("0.0.0.0:8151").String()
    logfile := kingpin.Flag("log", "log file").String()
    isActive := kingpin.Flag("active", "lis active").Bool()
    
    kingpin.Parse()
    if *logfile != "" {
        w := cronowriter.MustNew(*logfile + ".%Y%m%d%H%M")
        glg.Get().SetMode(glg.WRITER).SetWriter(w)
    }
    am, err := server.NewSimpleAuthManager(*authCfg)
    if err != nil {
        glg.Errorf("load auth file %s , error: %v", *authCfg, err)
        return
    }
    sid := "meta0"
    
    lm := server.NewLeaseManager(pb.Role_MetaServer, sid, 10, am)
    
    ms := &MetaServer{
        sid:          sid,
        leaseManager: lm,
        isActive:     *isActive,
    }
    
    lis, err := net.Listen("tcp", *addr)
    if err != nil {
        glg.Errorf("failed to listen on %s ,error: %v", *addr, err)
        return
    }
    defer lis.Close()
    srv := grpc.NewServer()
    pb.RegisterMetaServiceServer(srv, ms)
    pb.RegisterBaseServerServer(srv, ms)
    glg.Infof("meta server started on %s, is active: %v", *addr, *isActive)
    
    if err := srv.Serve(lis); err != nil {
        glg.Errorf("meta server error: %v", err)
    }
}
